/*!
 * override ajax
 * 覆盖jq的ajax方法 代理我们的代码
 * --------如果未引用header模块，且页面是开放的，请引用此文件
 * @author Sherlock 
 */
define( [ 'jquery', 'login', 'message', 'bootstrap' ], function( $, login, ShowTitleMessage ) {
  var showTime = ShowTitleMessage.showTime;
  var ajaxBackup = $.ajax;

  $.ajax = function( url, options ) {

    if ( typeof url === 'object' ) {
      options = url;
      url = undefined;
    }

    options = options || {};

    var completeBackUp = options.complete,
      successBackup = options.success,
      errorBackup = options.error;
    var urlBackup = url;
    var optionBackup = $.extend( {}, options );

    options.complete = function() {
      if ( $.isFunction( completeBackUp ) ) {
        completeBackUp.apply( options.context, arguments );
      }
    };
    options.success = function( data ) {

      var tempData;
      try {
        tempData = typeof data === 'string' ? ( $.parseJSON( data ) || {} ) : ( data || {} );
      } catch ( e ) {
        tempData = {};
      }

      var ret = tempData.ret * 1;
      if ( ret === 911 ) { // 未登录的状态码
        $( '.modal.in' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
        login.$selector.one( 'shown.bs.modal', function() {
          ShowTitleMessage.hide();
        } ).modal( 'show' );
        if ( successBackup ) {
          login.loginSuccessAndContinue = function() {
            $.ajax( urlBackup, optionBackup );
          };
        }
        return;
      } else if ( ret === 44444 ) { // 权限不足状态码
        ShowTitleMessage.showWarning( tempData.msg, showTime );
        setTimeout( function() {
          $( "#register-guide" ).modal( "show" )
        }, 100 );
      }

      if ( $.isFunction( successBackup ) ) {
        successBackup.apply( options.context, arguments );
      }
    }
    options.error = function() {
      if ( $.isFunction( errorBackup ) ) {
        errorBackup.apply( options.context, arguments );
      }
    }

    return url ? ajaxBackup( url, options ) : ajaxBackup( options );
  }

  return $.ajax;
} );